﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;

namespace VoirEspaceDisk
{
    public partial class FenetrePrincipale : Form
    {
        enum Index
        {
            DefaultImage = 0,
            ClosedFolder = 1
        }

        Dictionary<string, long> TailleDossier = new Dictionary<string, long>();
        int Bornes = 0; // 0, pas de règle, sinon 1 ou 2
        long Borne1 = 0;
        long Borne2 = 0;

        public FenetrePrincipale()
        {
            InitializeComponent();
            DateTime debut = DateTime.Now;
#if Blingbling
            treeView1.ShowPlusMinus = false;
            ImageList imageList = new ImageList();
            imageList.Images.Add(ProjectResources.file);
            imageList.Images.Add(ProjectResources.dossier_fermé);
            treeView1.ImageList = imageList;

            treeView1.NodeMouseClick += new TreeNodeMouseClickEventHandler(treeView1_NodeMouseClick);
            treeView1.NodeMouseDoubleClick += new TreeNodeMouseClickEventHandler(treeView1_NodeMouseDoubleClick);
#endif
            TimeSpan ts = new TimeSpan(DateTime.Now.Ticks - debut.Ticks);
            textBoxPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

            ajouterDossierToolStripMenuItem.Visible = false;
            rechercheToolStripMenuItem.Visible = false;
        }

        void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            Point p = e.Location;
            if (e.Node.IsExpanded)
            {
                e.Node.Collapse();
            }
            else
            {
                e.Node.Expand();
            }
        }

        void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            string t = e.Node.Name;
            string r = e.Node.Text;
            if (File.Exists(e.Node.Name) || Directory.Exists(e.Node.Name))
            {
                Process.Start(e.Node.Name);
            }
        }

        public void add_tree_nodes(string path, TreeNode current)
        {
            // liste les fichiers du répertoire courant
            DirectoryInfo di = new DirectoryInfo(path);
            try
            {
                foreach (FileInfo fileinfo in di.GetFiles())
                {
                    string node_display = fileinfo.Name;
                    if (fileinfo.Length > 0)
                    {
                        node_display += " [" + format_rep_size(fileinfo.Length) + "]";
                    }
                    TreeNode node_tmp = new TreeNode(node_display, (int)Index.DefaultImage, (int)Index.DefaultImage);
                    node_tmp.Name = fileinfo.FullName;
                    current.Nodes.Add(node_tmp);
                }
            }
            catch (UnauthorizedAccessException uae)
            {
                //output.WriteLine("access interdit");
            }
            try
            {
                foreach (DirectoryInfo dossier in di.GetDirectories())
                {
                    string rep_display = dossier.Name;
                    long rep_length = rep_size(dossier.FullName);
                    if (rep_length > 0)
                    {
                        rep_display += " [";
                        rep_display += format_rep_size(rep_length);
                        rep_display += "]";
                    }
                    TreeNode node = new TreeNode(rep_display, (int)Index.ClosedFolder, (int)Index.ClosedFolder);
                    node.Name = dossier.FullName;
                    add_tree_nodes(dossier.FullName, node);
                    current.Nodes.Add(node);
                }
            }
            catch (UnauthorizedAccessException uae)
            {
                //output.WriteLine("access interdit");
            }
        }

        public long rep_size(string path)
        {
            DirectoryInfo di = new DirectoryInfo(path);
            long dir_files_size = 0;
            try
            {
                foreach (FileInfo fileinfo in di.GetFiles())
                {
                    dir_files_size += fileinfo.Length;
                }
            }
            catch (UnauthorizedAccessException uae) { }
            try
            {
                foreach (DirectoryInfo dossier in di.GetDirectories())
                {
                    long taille = 0;
                    if (TailleDossier.TryGetValue(path, out taille))
                    {
                        dir_files_size = taille;
                    }
                    else
                    {
                        dir_files_size += rep_size(dossier.FullName);
                    }
                }
            }
            catch (UnauthorizedAccessException uae) { }
            if (!TailleDossier.ContainsKey(path))
            {
                TailleDossier.Add(path, dir_files_size);
            }
            return dir_files_size;
        }

        public string format_rep_size(long size)
        {
            string result = size.ToString();
            result += " o";
            if (size > 1000 && size < 1000000)
            {
                result = (size / 1000).ToString("0.00") + " Ko";
            }
            if (size > 1000000 && size < 1000000000)
            {
                result = (size / 1000000).ToString("0.00") + " Mo";
            }
            if (size > 1000000000)
            {
                result = (size / 1000000000).ToString("0.00") + " Go";
            }
            return result;
        }

        private void quitterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void règleDeRechercheToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RegleRecherche regle = new RegleRecherche();
            if (regle.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Bornes = regle.NombreBornes;
                Borne1 = regle.Borne1;
                Borne2 = regle.Borne2;
            }
        }

        private void buttonAjouter_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(textBoxPath.Text))
            {
                progressBar1.Style = ProgressBarStyle.Marquee;
                buttonAjouter.Enabled = false;

                BackgroundWorker bgw = new BackgroundWorker();
                bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
                bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
                bgw.RunWorkerAsync();
            }
            else
            {
                MessageBox.Show("Le répertoire n'existe pas !\r\nVérifier le chemin d'accès.",
                    "Erreur de chemin", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            NewNode = new TreeNode(textBoxPath.Text, (int)Index.ClosedFolder, (int)Index.ClosedFolder);
            add_tree_nodes(textBoxPath.Text, NewNode);
        }

        void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            treeView1.Nodes.Add(NewNode);
            buttonAjouter.Enabled = true;
            progressBar1.Style = ProgressBarStyle.Blocks;
        }

        TreeNode NewNode;

        private void treeView1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                treeView1_NodeMouseDoubleClick(this,
                    new TreeNodeMouseClickEventArgs(treeView1.SelectedNode, System.Windows.Forms.MouseButtons.Right,0, 0, 0));
            }
        }

        private void textBoxPath_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                buttonAjouter_Click(this, new EventArgs());
            }
        }
    }
}
